package com.yy.young.ums.web;

import com.yy.young.base.exception.YoungBaseException;
import com.yy.young.base.util.GlobalConstants;
import com.yy.young.common.config.DomainHandler;
import com.yy.young.common.util.*;
import com.yy.young.dal.util.Page;
import com.yy.young.interfaces.log.annotation.Log;
import com.yy.young.interfaces.model.User;
import com.yy.young.ums.model.LGLog;
import com.yy.young.ums.model.UserStatistics;
import com.yy.young.ums.service.IUmsConfigService;
import com.yy.young.ums.service.IUmsLGLogService;
import com.yy.young.ums.service.IUmsUserService;
import com.yy.young.ums.util.SecureHandler;
import com.yy.young.ums.util.UmsConfigHelper;
import com.yy.young.ums.util.UmsConstants;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 * Created by Administrator on 2017/5/8.
 */
@Controller
@RequestMapping("/ums/user")
public class UmsUserController {

    @Resource(name="umsUserService")
    IUmsUserService userService;

    @Resource(name="umsLGLogService")
    IUmsLGLogService umsLGLogService;


    private static Logger logger = LoggerFactory.getLogger(UmsUserController.class);

    /**
     * 权限处理
     * @param parameter 参数集
     * @param request 请求对象
     * @throws Exception 用户登录超时会抛出异常
     */
    private void authHandle(Map<String,Object> parameter, HttpServletRequest request) throws Exception{
        User user = CommonUtil.getLoginUser(request);
        if (user == null){
            throw new YoungBaseException("-101", "登录超时!");
        }
        //管理范围,默认从参数中取
        String rangeId = CommonUtil.getDefaultValue(parameter.get("RANGE_ID")+"", user.getRangeId());
        if (StringUtils.isBlank(rangeId)){
            rangeId = user.getCompanyId();
        }
        parameter.put("RANGE_ID", rangeId);
    }

    /**
     * 获取用户列表
     * @param request
     * @return
     * @throws Exception
     */
    @Log("查询用户列表")
    @RequestMapping("/getUserList")
    @ResponseBody
    public Object getUserList(HttpServletRequest request) throws Exception{
        Map<String,Object> parameter = CommonUtil.getParameterFromRequest(request);
        authHandle(parameter, request);//权限处理
        List<Map<String,Object>> list = userService.getUserList(parameter);
        return new Result(list);
    }

    /**
     * 获取用户列表(分页)
     * @param request
     * @return
     * @throws Exception
     */
    @Log("分页查询用户列表")
    @RequestMapping("/getUserPage")
    @ResponseBody
    public Object getUserPage(HttpServletRequest request) throws Exception{
        Map<String,Object> parameter = CommonUtil.getParameterFromRequest(request);
        authHandle(parameter, request);//权限处理
        Page page = CommonUtil.getPageFromRequest(request);
        List<Map<String,Object>> list = userService.getUserPage(parameter,page);
        page.setData(list);
        //当存在callback跨域参数时,返回跨域格式结果
        if(StringUtils.isNotBlank(request.getParameter("callback"))){
            return request.getParameter("callback")+"("+CommonJsonUtil.bean2JsonStr(page)+");";
        }
        return page;
    }

    /**
     * 添加用户
     * @param request
     * @return
     * @throws Exception
     */
    @Log("添加用户")
    @RequestMapping("/insertUser")
    @ResponseBody
    public Object insertUser(HttpServletRequest request) throws Exception{
        Map<String,Object> parameter = CommonUtil.getParameterFromRequest(request);
        Result result = new Result();
        if(StringUtils.isBlank(parameter.get("COMPANY_ID")+"")){
            result.setCode(-1);
            result.setInfo("单位不允许为空!");
        }else{
            int num = userService.insertUser(parameter);
            if(num < 0){
                result.setCode(-1);
                result.setInfo("添加用户失败!");
            }
        }
        return result;
    }

    /**
     * 修改用户信息
     * @param request
     * @return
     * @throws Exception
     */
    @Log("修改用户")
    @RequestMapping("/updateUser")
    @ResponseBody
    public Object updateUser(HttpServletRequest request) throws Exception{
        Map<String,Object> parameter = CommonUtil.getParameterFromRequest(request);
        int num = userService.updateUser(parameter);
        Result result = new Result();
        if(num < 0){
            result.setCode(-1);
            result.setInfo("修改用户信息失败!");
        }
        return result;
    }

    /**
     * 删除用户信息
     * @param request
     * @return
     * @throws Exception
     */
    @Log("删除用户")
    @RequestMapping("/deleteUser")
    @ResponseBody
    public Object deleteUser(HttpServletRequest request) throws Exception{
        Map<String,Object> parameter = CommonUtil.getParameterFromRequest(request);
        int num = userService.deleteUser(parameter);
        Result result = new Result();
        if(num < 0){
            result.setCode(-1);
            result.setInfo("删除用户信息失败!");
        }
        return result;
    }

    /**
     * 重置密码
     * @param ids
     * @param request
     * @return
     * @throws Exception
     */
    @Log("重置密码")
    @RequestMapping("/resetPassword")
    @ResponseBody
    public Object resetPassword(String ids, HttpServletRequest request) throws Exception{
        Result result = new Result();
        if(StringUtils.isBlank(ids)){
            result.setCode(-1);
            result.setInfo("操作失败:待重置的用户编号为空!");
        }
        userService.resetPassword(ids);
        return result;
    }

    /**
     * 修改密码
     * @param oldPwd
     * @param newPwd
     * @return
     * @throws Exception
     */
    @Log("修改个人密码")
    @RequestMapping("/updatePassword")
    @ResponseBody
    public Object updatePassword(String oldPwd, String newPwd, HttpServletRequest request) throws Exception{
        Result result = new Result();
        if (StringUtils.isBlank(oldPwd) || StringUtils.isBlank(newPwd)){
            result.setCode(-1);
            result.setInfo("修改失败:旧密码或新密码为空!");
        }
        User user = (User)CommonUtil.getLoginUser(request);//当前登录用户信息
        if(user != null){
            user = userService.getUserById(user.getId());//查询最新用户信息
            if(SecureHandler.encrypt(oldPwd).equals(user.getPassword())){
                userService.updatePassword(user.getId(), newPwd);//修改密码
            }else{
                result.setCode(-1);
                result.setInfo("修改失败:旧密码错误!");
                logger.debug("[修改个人密码] 失败:旧密码错误!实际旧密码为:{},用户输入的旧密码为:{}(经过加密处理)!", user.getPassword(), SecureHandler.encrypt(oldPwd));
            }
        }else{
            result.setCode(-1);
            result.setInfo("修改失败:当前登录用户信息无效,请重新登录!");
        }

        return result;
    }

    /**
     * 查询我的信息
     * @param request
     * @return
     * @throws Exception
     */
    @Log("查询个人信息")
    @RequestMapping("/queryMyInfo")
    @ResponseBody
    public Object queryMyInfo(HttpServletRequest request) throws Exception{
        User user = CommonUtil.getLoginUser(request);//获取当前用户信息
        if (user != null && StringUtils.isNotBlank(user.getId())){
            user = userService.getUserById(user.getId());//查询用户信息
            user.setPassword("");//置空密码
        }
        return new Result(user);
    }

    /**
     * 查询我的统计信息,用于个人信息页展示
     * @param request
     * @return
     * @throws Exception
     */
    @Log("查询个人统计信息")
    @RequestMapping("/queryMyStatisticsInfo")
    @ResponseBody
    public Object queryMyStatisticsInfo(HttpServletRequest request) throws Exception{
        User user = CommonUtil.getLoginUser(request);//获取当前用户信息
        UserStatistics userStatistics = new UserStatistics();
        if (user != null && StringUtils.isNotBlank(user.getId())){
            user = userService.getUserById(user.getId());//查询用户信息
            user.setPassword("");//置空密码
            userStatistics.setUser(user);
            userStatistics.setLoginNum(umsLGLogService.countUserLoginNum(user));//设置用户登录数量
            //查询用户最后一次登录的日志
            LGLog lgLog = umsLGLogService.getUserLastLoginLog(user);
            if (lgLog != null){
                userStatistics.setLastLoginTime(lgLog.getLoginTime());//设置用户最后一次登录时间
                userStatistics.setLastLoginIp(lgLog.getClientIp());//设置用户最后一次登录的IP
            }
        }
        return new Result(userStatistics);
    }

    /**
     * 上传头像
     * @param file
     * @param request
     * @return
     * @throws Exception
     */
    @Log("上传个人头像")
    @RequestMapping("/uploadHeader")
    @ResponseBody
    public Object uploadHeader(MultipartFile file, HttpServletRequest request) throws Exception{
        Result result = new Result();
        User user = CommonUtil.getLoginUser(request);
        if (user != null){
            //传输文件
            String url = UmsConfigHelper.getConfigValue(UmsConstants.CONFIG_KEY.FS_TRANSFER_URL);//获取文件传输地址配置
            if (StringUtils.isBlank(url)){//若配置项为空,则使用默认配置
                url = CommonUtil.getDefaultValue(DomainHandler.get(GlobalConstants.URL_CONFIG_KEY.URL_FS), request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/");
                url += UmsConstants.FS.FS_TRANSFER_URI;// + "?folderId=" + UmsConstants.FS.FS_FOLDERID_HEADER;
            }
            String res = FsClientHelper.sendFiles(url, new MultipartFile[]{file});
            Result serverResult = CommonJsonUtil.jsonStr2Bean(res, Result.class);
            if (serverResult != null && serverResult.getCode() == 0){
                //传输成功,记录到用户表
                Map<String,Object> parameter = new HashMap<String, Object>();
                List list = serverResult.getData();
                if (list != null && list.size() > 0){
                    //传输文件返回的文件信息存放在data中
                    Map<String,Object> fileInfo = (Map)list.get(0);
                    parameter.put("HEADER", fileInfo.get("id"));
                    parameter.put("ID", user.getId());
                    userService.updateUser(parameter);
                }else{
                    result.setCode(-1);
                    result.setInfo("上传头像失败!");
                }
            }else{
                result.setCode(-1);
                result.setInfo("上传头像失败!");
            }
        }else{
            result.setCode(-1);
            result.setInfo("登录超时,请重新登录!");
        }

        return result;
    }

    /**
     * 根据单位查询用户
     * @param request
     * @return
     * @throws Exception
     */
    @Log("根据单位查询用户")
    @RequestMapping("/getUserListByCompanyId")
    @ResponseBody
    public Object getUserListByCompanyId(String companyId, HttpServletRequest request) throws Exception{
        Result result = new Result();
        if(StringUtils.isBlank(companyId)){
            result.setCode(-1);
            result.setInfo("单位编号不允许为空!");
        }else{
            result.setData(userService.getUserListByCompanyId(companyId));
        }

        return result;
    }
}
